package com.project.business.api;

import com.project.business.entity.FileEntity;
import com.project.business.service.FileEntityService;
import com.common.common.Response;
import jdk.jfr.Description;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.DownloadedFile;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;
import java.io.IOException;

@Mapping("/file")
@Controller
public class FileResource {

    @Inject
    private FileEntityService fileService;

    @Get
    @Mapping("/{id}")
    @Description("获取文件详情信息")
    public FileEntity get(@Param("id") Integer id) {
        return fileService.getOneById(id);
    }


    @Delete
    @Mapping("/{id}")
    @Description("删除文件信息")
    public Response del(@Param("id") Integer id) {
        fileService.del(id);
        return Response.successDel();
    }

    @Post
    @Mapping("/upload")
    @Description("上传文件")
    public FileEntity upload(UploadedFile file) {
        return fileService.upload(file);
    }

    @Get
    @Mapping("/{id}/download")
    @Description("下载文件")
    public void download(@Param("id") Integer id, Context ctx) throws IOException {
        File file = fileService.download(id);
        //简化写法
        DownloadedFile df = new DownloadedFile(file);

        //不做为附件下载（按需配置）
        df.asAttachment(true);

        ctx.outputAsFile(df);
    }

    @Get
    @Mapping("/{id}/preview")
    @Description("预览查看文件")
    public void preview(@Param("id") Integer id, Context ctx) throws IOException {
        File file = fileService.preview(id);
        //简化写法
        DownloadedFile df = new DownloadedFile(file);

        //不做为附件下载（按需配置）
        df.asAttachment(false);

        ctx.outputAsFile(df);
    }

}
